package com.mlt.back.service.impl;
import com.mlt.back.beans.Manager;
import com.mlt.back.dao.ManagerDao;
import com.mlt.back.dao.Manager_RoleDao;
import com.mlt.back.dao.impl.ManagerDaoImpl;
import com.mlt.back.dao.impl.Manager_RoleDaoImpl;
import com.mlt.back.exceptions.NotFindException;
import com.mlt.back.exceptions.WrongValueException;
import com.mlt.back.service.ManagerService;
import com.mlt.back.utils.MD5Util;

import java.util.List;

public class ManagerServiceImpl implements ManagerService {
    private ManagerDao managerDao=new ManagerDaoImpl();
    private Manager_RoleDao manager_roleDao=new Manager_RoleDaoImpl();
    //实现用户登录功能
    @Override
    public Manager doLogin(String login_name, String login_pwd)
            throws NotFindException, WrongValueException {
        Manager manager = managerDao.selectByLoginName(login_name);
        //判断是否存在用户
        if (manager==null){
            throw new NotFindException("未查询到用户，请确认是否注册！");
        }
        //判断密码是否正确
        String pwd= MD5Util.getMD5(login_pwd);
        if (pwd.equals(manager.getLogin_pwd())){
            return manager;
        }else {
            throw new WrongValueException("密码错误");
        }
    }

    @Override
    public int addManager(Manager manager, String role_id) {
        int count=0;
        //修改密码为加密模式
        String mm=MD5Util.getMD5(manager.getLogin_pwd());
        manager.setLogin_pwd(mm);
        //更新t_manager表
        count+=managerDao.insert(manager);
        if (count==1){
            System.out.println("添加管理员成功");
        }
        Manager manager1 = managerDao.selectByLoginName(manager.getLogin_name());
        //更新t_mgr_role表
        count+=manager_roleDao.insert(manager1.getMgr_id(),role_id);
        if (count==2){
            System.out.println("添加管理员角色关系成功");
        }
        return count;
    }

    @Override
    public String doCheck(String name, String value) {
        String findName=null;
        findName=managerDao.doCheck(name,value);
        return findName;
    }

    @Override
    public List<Manager> selectByRole(String role_id, int page) {
        List<Manager> managerList=managerDao.selectByRole(role_id,page);
        return managerList;
    }

    @Override
    public void del(int mgr_id) {
        managerDao.del(mgr_id);
    }

    @Override
    public Manager selectById(String mgr_id) {
        Manager manager=managerDao.selectById(mgr_id);
        return manager;
    }

    @Override
    public void update(Manager manager, String role_id) {
        manager_roleDao.update(manager.getMgr_id(),role_id);
        managerDao.update(manager);
    }
}
